package com.xneure.code.image;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import com.xneure.utils.ImgUtil;

/**
 * 图片工具类， 图片水印，文字水印，缩放，补白等
 */
public class WaterMark{

	/**
	 * 图片添加水印
	 * 
	 * @param srcImgPath 需要添加水印的图片的路径
	 * @param outImgPath 添加水印后图片输出路径
	 * @param markContentColor 水印文字的颜色
	 * @param waterMarkContent 水印的文字
	 * @return
	 */
	public static BufferedImage mark(String srcImgPath,Color markContentColor,String waterMarkContent){
		return mark(new File(srcImgPath),markContentColor,waterMarkContent);
	}

	public static BufferedImage mark(InputStream is,Color markContentColor,String waterMarkContent){
		try{
			// 读取原图片信息
			Image srcImg = ImageIO.read(is);
			int srcImgWidth = srcImg.getWidth(null);
			int srcImgHeight = srcImg.getHeight(null);
			// 加水印
			BufferedImage bufImg = new BufferedImage(srcImgWidth,srcImgHeight,BufferedImage.TYPE_INT_RGB);
			Graphics2D g = bufImg.createGraphics();
			g.drawImage(srcImg,0,0,srcImgWidth,srcImgHeight,null);
			int size = Math.min(srcImgHeight,srcImgWidth) / 3;
			Font font = new Font("宋体",Font.PLAIN,size);
			g.setColor(markContentColor); // 根据图片的背景设置水印颜色
			g.setFont(font);
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,.3f));
			g.rotate(Math.toRadians(-45),(double)srcImgWidth / 2,(double)srcImgHeight / 2);
			int x = getWatermarkLength(waterMarkContent,g);
			g.drawString(waterMarkContent,(srcImgWidth - x) / 2,(srcImgHeight) / 2 + (size / 3));
			g.dispose();
			// 输出图片
			return bufImg;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public static BufferedImage mark(File srcImgFile,Color markContentColor,String waterMarkContent){
		try{
			return mark(new FileInputStream(srcImgFile),markContentColor,waterMarkContent);
		}catch(FileNotFoundException e){
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取水印文字总长度
	 * 
	 * @param waterMarkContent 水印的文字
	 * @param g
	 * @return 水印文字总长度
	 */
	public static int getWatermarkLength(String waterMarkContent,Graphics2D g){
		return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(),0,waterMarkContent.length());
	}

	public static void main(String[] args) throws IOException{
		FileOutputStream fos = new FileOutputStream("d:/tmp.jpg");
		BufferedImage bufImg = WaterMark.mark("D:/1.jpg",Color.blue,"oojz");
		// BufferedImage bufImg = ImageUtils.zoom(new File("D:/1.jpg"), 1500,
		// 1500);
		ImgUtil.save(fos,bufImg);
	}
}
